package com.example.controller;

import com.example.exception.DatabaseConfigurationException;
import com.example.exception.DatabaseConnectionException;
import com.example.exception.SqlExceptionHandler;
import com.example.model.DbConnectionRequest;
import com.example.model.ErrorResponse;
import com.example.service.DbConnectionService;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.UnknownHostException;
import java.sql.SQLException;

@RestController
@RequestMapping("/db")
public class DbController {
	private static final Logger logger = LoggerFactory.getLogger(DbController.class);
	private final DbConnectionService dbConnectionService;
	private final SqlExceptionHandler sqlExceptionHandler;

	@Autowired
	public DbController(DbConnectionService dbConnectionService, SqlExceptionHandler sqlExceptionHandler) {
		this.dbConnectionService = dbConnectionService;
		this.sqlExceptionHandler = sqlExceptionHandler;
	}

	@PostMapping("/test-connection")
	public ResponseEntity<Void> testConnection(@Valid @RequestBody DbConnectionRequest request) {
		logger.info("收到数据库连接测试请求: {}", request.getUrl());
		
		try {
			dbConnectionService.testConnection(request.getUrl(), request.getUsername(), request.getPassword());
			logger.info("数据库连接测试成功");
			return ResponseEntity.ok().build();
		} catch (SQLException ex) {
			logger.warn("数据库连接测试失败，SQL异常: {}", ex.getMessage());
			
			// 使用专门的 SQL 异常处理器进行分类
			ResponseEntity<ErrorResponse> errorResponse = sqlExceptionHandler.handleSqlException(ex);
			
			// 根据错误类型抛出相应的自定义异常
			if (errorResponse.getStatusCode().is4xxClientError()) {
				throw new DatabaseConfigurationException("数据库配置错误");
			} else {
				throw new DatabaseConnectionException("数据库连接错误");
			}
		}
	}
} 